<template>
  <div class="hello-container">
    <lemon-imui :simple="true" :avatar-cricle="true" :hide-message-name="false" :hide-message-time="false" :user="userData" :contextmenu="msgContextmenu" @pull-messages="handlePullMessages" @change-contact="handleChangeContact" @send="handleSend" ref="IMUI" />
    <DialogOfAccount :visible="dialogOfAccount" :chatType="chatType" :accountId="accountId" @success="login" @closeDialog="closeDialog" />
  </div>
</template>

<script>
// 生成消息唯一索引
const generateRandId = () => {
  return Math.random().toString(36).substr(-8);
};
import EmojiData from "../database/emoji";
import MyWebSocket from "./MyWebsocket";
import { mapState } from "vuex";
import { getCookie, setCookie } from "@/utils/auth";
import DialogOfAccount from "./DialogOfAccount";
export default {
  name: "HomeView",
  components: { DialogOfAccount },
  props: {
    msg: String,
  },
  computed: {
    ...mapState({
      userData: (state) => state.user.userData,
      contactsData: (state) => state.contacts.contactsData,
      messageList: (state) => state.messageList.messageList,
    }),
    hasLogin() {
      return getCookie() || this.accountId;
    },
  },
  data() {
    return {
      websocket: null,
      currentContactId: 1, //当前联系人id
      chatType: "chat", // chat |  code
      accountId: "",
      repeatStr: "欢迎体验AI聊天,made by 胖虎,晓月 Email:fengkuangdejava@outlook.com,luxiaoyue@qq.com",
      dialogOfAccount: false,
      unLoginMsgObj: {}, //未登录前，发送的消息
      msgContextmenu: [
        {
          text: "删除",
          color: "red",
          icon: "",
          click(e, instance, hide) {
            console.log("删除", e, instance);
            let {
              message: { id },
            } = instance;
            let that = instance.IMUI.$parent;
            that.removeMessage(id);
            hide();
          },
          render() {},
        },
      ],
      websocketIsError: false,
    };
  },
  mounted() {
    this.initChat();
    this.accountId = getCookie() ? getCookie() : "";
    if (this.accountId) this.initWebsocket();
  },
  methods: {
    login({ chatType, accountId }) {
      this.chatType = chatType;
      this.accountId = accountId;
      if (this.websocket) this.websocket.close();
      setCookie(this.accountId);
      this.initWebsocket();
    },
    initChat() {
      if (this.hasLogin) this.$store.dispatch("messageList/initMsgList", { id: this.currentContactId });
      if (this.$refs.IMUI) {
        this.$refs.IMUI.initContacts(this.contactsData);
        // this.$refs.IMUI.initEmoji(EmojiData);
        // 自定义工具栏
        this.initEditorTools();
        this.$refs.IMUI.changeContact(this.currentContactId);
      }
    },
    initEditorTools() {
      let that = this;
      let tools = [
        {
          name: "changeChatType",
          isRight: false,
          title: "切换模式",
          click: () => {
            that.dialogOfAccount = true;
          },
          render: () => {
            return <span style="color:#333">切换模式</span>;
          },
        },
        {
          name: "clearHistory",
          isRight: false,
          title: "清空所有记录",
          click: () => {
            that.removeAllMessage();
          },
          render: () => {
            return <span style="color:red">清空所有记录</span>;
          },
        },
      ];
      this.$refs.IMUI.initEditorTools(tools);
    },
    initWebsocket() {
      let that = this;
      this.websocket = new MyWebSocket("messagePusher", {
        params: {
          url: `ws://124.220.38.75:8079/websocket/${this.chatType}/${this.accountId}`,
          // 124.220.38.75/
        },
        onmessage: function (messagestr) {
          console.log("messagestr", messagestr);
          if (messagestr.indexOf("密码不对,聊天关闭,请修改设置") > -1) {
            that.websocketIsError = true;
            that.websocket.close();
            that.validateAccount();
            return;
          } else {
            that.websocketIsError = false;
          }
          console.log("that.messageList[that.currentContactId]", that.messageList[that.currentContactId]);
          if (messagestr == that.repeatStr && !that.messageList[that.currentContactId].find((i) => i.content == that.repeatStr)) that.createMsgObj(messagestr);
          if (messagestr !== that.repeatStr) that.createMsgObj(messagestr);
        },
        onopen: function (res) {
          console.log("onopen", "SOCKET已连接上...");
          if (JSON.stringify(that.unLoginMsgObj) != "{}") {
            setCookie(that.accountId);
            that.appendMessage(that.unLoginMsgObj);
            that.unLoginMsgObj = {};
          }
        },
        onclose: function (event) {
          console.log("onclose SOCKET连接关闭", event);
          if (false) {
            //是否重连
            that.websocket.reconnect();
          }
        },
        onerror: function (err) {
          console.log("ws onerror 消息", err);
        },
      });
    },
    // 根据id获取联系人信息
    getContact(id) {
      const data = this.contactsData.find((contact) => contact.id == id);
      return { id: data.id, avatar: data.avatar, displayName: data.displayName };
    },
    createMsgObj(msgStr) {
      let that = this;
      let fromUserObj = that.getContact(this.currentContactId);
      let msgObj = {
        id: generateRandId(),
        status: "succeed",
        type: "text",
        sendTime: new Date().getTime(),
        content: msgStr,
        toContactId: this.currentContactId, //接收消息的联系人ID
        fromUser: fromUserObj,
      };
      this.appendMessage(msgObj);
    },
    handlePullMessages(contact, next) {
      console.log("handlePullMessages", contact);
      next(this.messageList[contact.id], true); //历史消息
    },
    handleChangeContact() {},
    handleSend(message, next, file) {
      if (!this.hasLogin || this.websocketIsError) {
        this.dialogOfAccount = true;
        this.unLoginMsgObj = message;
        next({ status: "succeed" });
        this.removeMessage(message.id);
        return;
      } else {
        this.unLoginMsgObj = {};
      }
      this.websocket.send(message.content);
      next();
      this.$store.dispatch("messageList/pushMsg", { id: this.currentContactId, msgObj: message });
    },
    closeDialog(dialog) {
      this[dialog] = false;
    },
    getMessages(contactId) {
      let msgList = this.$refs.IMUI.getMessages(contactId);
      return msgList;
    },
    getEditorValue() {
      return this.$refs.IMUI.getEditorValue();
    },
    // 设置编辑框内容
    setEditorValue(str) {
      this.$refs.IMUI.setEditorValue(str);
    },
    appendMessage(msgObj) {
      this.$refs.IMUI.appendMessage(msgObj, true);
      this.$store.dispatch("messageList/pushMsg", { id: this.currentContactId, msgObj });
    },
    removeAllMessage() {
      let msgList = JSON.parse(JSON.stringify(this.getMessages(this.currentContactId)));
      msgList.forEach((msgObj) => {
        this.removeMessage(msgObj.id);
      });
      this.$store.dispatch("messageList/initMsgList", { id: this.currentContactId, initMsgList: [] });
    },
    removeMessage(msgId) {
      this.$refs.IMUI.removeMessage(msgId);
      this.$store.dispatch("messageList/removeMsgById", { id: this.currentContactId, msgId });
    },
    validateAccount() {
      this.$alert("密码不对,聊天关闭,请修改设置", "提示")
        .then(() => {
          this.dialogOfAccount = true;
        })
        .catch(() => {});
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.hello-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  padding: 24px;
  background-image: url(@/assets/bg.png);
  background-size: 130% 110%;

  ::v-deep .lemon-wrapper {
    border-radius: 10px;
    overflow: hidden;
  }
  ::v-deep .lemon-editor {
    border-top: 1px solid #ccc;
  }
}
</style>
